import {Button, message} from 'antd';
import React, {useState, useRef} from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import ProTable, { ProColumns, ActionType } from '@ant-design/pro-table';
import {EnvShow, EnvCreateParam, EnvDeleteParam} from './data.d';
import {queryEnvs, removeEnv, createEnv} from './service';
import {PlusOutlined} from "@ant-design/icons";
import CreateForm from './components/CreateForm';
import EnvDeleteForm from './components/EnvDeleteForm';

/**
 * 创建instance
 * @param fields
 */
const handleCreateEnv = async (fields: EnvCreateParam) => {
  const hide = message.loading('正在提交环境创建...');
  try {
    await createEnv({ ...fields });
    hide();
    message.success('提交成功');
    return true;
  } catch (error) {
    hide();
    message.error('提交创建环境失败, 请重试！');
    return false;
  }
};

/**
 * 删除instance
 * @param fields
 */
const handleRemoveEnv = async (fields: EnvDeleteParam) => {
  const hide = message.loading('正在删除...');
  try {
    await removeEnv({
      ...fields
    });
    hide();
    message.success('删除成功');
    return true;
  } catch (error) {
    hide();
    message.error('删除失败请重试！');
    return false;
  }
};

const TableList: React.FC<{}> = () => {
  const [createEnvModalVisible, setCreateEnvModalVisible] = useState<boolean>(false);
  const [deleteModalVisible, setDeleteModalVisible] = useState<boolean>(false);
  const [deleteEnvValues, setDeleteEnvValues] = useState<EnvDeleteParam>({});
  const actionRef = useRef<ActionType>();
  /*
  const [row, setRow] = useState<KConfigItem>();
  */

  const columns: ProColumns<EnvShow>[] = [
    {title: 'id', dataIndex: 'id'},
    {title: 'name', dataIndex: 'name'},
    {title: 'user', dataIndex: 'user'},

    {title: 'jenkinsState', dataIndex: 'jenkinsState'},
    {title: 'nginxState', dataIndex: 'nginxState'},
    {title: 'dbState', dataIndex: 'dbState'},
    {title: 'redisState', dataIndex: 'redisState'},
    /*
    {title: 'userUrl', dataIndex: 'userUrl'},
    {title: 'adminUrl', dataIndex: 'adminUrl'},
    {title: 'mobileUrl', dataIndex: 'mobileUrl'},
     */

    {title: 'accessIP', dataIndex: 'accessIP'},
    {title: 'dbName', dataIndex: 'dbName'},
    {title: 'dbUser', dataIndex: 'dbUser'},
    {title: 'dbPort', dataIndex: 'dbPort'},
    {title: 'redisPort', dataIndex: 'redisPort'},


    {title: 'date', dataIndex: 'date'},
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      key: 'operation',
      render: (_, record) => (
        <>
          <a onClick={() => {
            setDeleteModalVisible(true);
            setDeleteEnvValues({id: record.id, envName: record.name})}}
          >删除</a>
        </>
      ),
    },
  ];

  return (
    <PageContainer>
      <ProTable<EnvShow>
        actionRef={actionRef}
        rowKey="id"
        request={() => queryEnvs()}
        columns={columns}
        search={false}
        /*
        options={false} */
        pagination={false}
        scroll={{ x: 1300 }}
        toolBarRender={() => [
          <Button key="1" type="primary" onClick={() => setCreateEnvModalVisible(true)}>
            <PlusOutlined /> 新建
          </Button>,
        ]}
      />

      <CreateForm
        onSubmit={async (value) =>{
          const success = await handleCreateEnv(value);
          if (success) {
            setCreateEnvModalVisible(false);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
        onCancel={() => setCreateEnvModalVisible(false)}
        createEnvModalVisible={createEnvModalVisible}
      />

      {deleteEnvValues && Object.keys(deleteEnvValues).length ? (
        <EnvDeleteForm
          onSubmit={async (value) => {
            const success = await handleRemoveEnv(value);
            if (success) {
              setDeleteModalVisible(false);
              setDeleteEnvValues({});
              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
          onCancel={() => {
            setDeleteModalVisible(false);
            setDeleteEnvValues({});
          }}
          deleteModalVisible={deleteModalVisible}
          values={deleteEnvValues}
        />
      ) : null}

    </PageContainer>
  );
};

export default TableList;
